//
//  CCLoginViewController.m
//  Party
//
//  Created by coco on 15/4/7.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCLoginViewController.h"
#import "CCLoginViewModel.h"

@interface CCLoginViewController()
@property (strong, nonatomic) CCLoginViewModel *viewModel;
@end

@implementation CCLoginViewController

- (id) initWithViewModel:(id)viewModel {
  if (self = [super initWithViewModel:viewModel]) {
    _viewModel = viewModel;
  }
  return self;
}

- (void) viewDidLoad {
  [self setupUI];
  [self viewWithCSS];
  [self bindWithViewModel];
  self.view.backgroundColor = [UIColor lightGrayColor];
  [super viewDidLoad];
}

- (void) setupUI {
  VIEW(
       self.nameTextField = [[UITextField alloc] init];
       self.nameTextField.backgroundColor = [UIColor whiteColor];
      )
  VIEW(
       self.passwordTextField = [[UITextField alloc] init];
       self.passwordTextField.backgroundColor = [UIColor whiteColor];
       self.passwordTextField.secureTextEntry = YES;
      )
  VIEW(
       self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
       [self.loginButton setTitle:@"登陆" forState:UIControlStateNormal];
      )
  [self.view addSubview: self.nameTextField];
  [self.view addSubview: self.passwordTextField];
  [self.view addSubview: self.loginButton];
}

-(void) viewWithCSS {
  [self.nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(@50);
    make.top.mas_equalTo(@50);
    make.size.mas_equalTo(CGSizeMake(200, 50));
  }];
  
  [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(@50);
    make.top.mas_equalTo(@120);
    make.size.mas_equalTo(CGSizeMake(200, 50));
  }];
  
  [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(@50);
    make.top.mas_equalTo(@190);
    make.size.mas_equalTo(CGSizeMake(200, 50));
  }];
  
}

- (void) bindWithViewModel {
  self.loginButton.rac_command = self.viewModel.loginCommand;
  RAC(self.viewModel, name) = self.nameTextField.rac_textSignal;
  RAC(self.viewModel, password) = self.passwordTextField.rac_textSignal;
  RAC(self.nameTextField,placeholder) = RACObserve(self.viewModel, namehold);
  RAC(self.passwordTextField,placeholder) = RACObserve(self.viewModel, passwordhold);
  [self.viewModel.loginSignal subscribeNext:^(id x) {
    if (x == nil) {
      MBProgressHUD *HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      HUB.labelText = @"请稍后...";
    } else {
      [MBProgressHUD hideHUDForView:self.view animated:YES];
//      [self.navigationController popViewControllerAnimated:YES];      
    }

  } error:^(NSError *error) {
  } completed:^{
  }];
  
}

- (void) dealloc {
    NSLog(@"login view dealloc");
}
@end
